import { throttle } from 'lodash-es'
import type { Ref } from 'vue'
import type { VChartInstance } from '@/types'

export function useChartAutoResize(
  chartRef: Ref<VChartInstance | undefined>,
) {
  const resizeHandler = throttle(() => {
    chartRef.value?.resize({
      animation: {
        duration: 1000,
      },
    })
  })

  function addListener() {
    window.addEventListener('resize', resizeHandler, false)
  }

  function removeListener() {
    window.removeEventListener('resize', resizeHandler)
  }

  onMounted(() => {
    addListener()
  })

  onBeforeUnmount(() => {
    removeListener()
  })
}
